import React, { useState, useEffect } from "react";
import { Layout, Menu, Breadcrumb, theme, MenuProps, Button } from "antd";
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { Outlet, useNavigate, useLocation } from "react-router-dom";

// import useResize from "../hooks/useResize"
//// eslint-disable-next-line react-hooks/rules-of-hooks
// useResize()
import routerList from "../router/index";
const { Header, Content, Footer, Sider } = Layout;


// 定义路由项类型
interface RouteItem {
  path: string;
  name: string;
  routeyi?: string;
  routeer?: string;
  children?: RouteItem[];
  nameer: string;
}

// 构建路由树
function buildRouteTree(routes: RouteItem[]): RouteItem[] {
  const tree: RouteItem[] = [];
  const routeMap = new Map<string, RouteItem>();
  if(!routes){
    routes=[]
  }
  routes.forEach((route) => {
    const parentPath = route.routeyi;
    if (typeof parentPath === "undefined") {
      return; // 跳过这次循环
    }
    const node: RouteItem = {
      path: route.routeer || "",
      name: route.nameer,
      children: [],
      nameer: "",
    };
    routeMap.set(node.path, node);
    if (!routeMap.has(parentPath)) {
      routeMap.set(parentPath, {
        path: parentPath,
        name: route.nameyi,
        children: [],
        nameer: "",
      });
    }
    const parentNode = routeMap.get(parentPath);
    if (parentNode) {
      parentNode.children.push(node);
    }
  });
  routeMap.forEach((node) => {
    if (!routeMap.has(node.path.substring(0, node.path.lastIndexOf("/")))) {
      tree.push(node);
    }
  });
  return tree;
}
// 生成菜单项
function generateMenuItems(routes: RouteItem[]): MenuProps["items"] {
  const iconMap: Record<string, React.ReactNode> = {
    首页: <DesktopOutlined />,
    数据图: <PieChartOutlined />,
    文章: <FileOutlined />,
    团队: <TeamOutlined />,
    用户: <UserOutlined />,
  };

  return routes.map((route) => {
    const { path, name, children } = route;
    const icon = iconMap[name] || <UserOutlined />;
    const menuItem: MenuProps["items"][number] = {
      key: path,
      label: (
        <span>
          {icon} {name}
        </span>
      ),
      path: path,
    };
    if (children && children.length > 0) {
      menuItem.children = generateMenuItems(children);
    }
    return menuItem;
  });
}
const Home: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [routes, setRoutes] = useState<RouteItem[]>([]);
  const navigate = useNavigate();

  const rbaclogin = localStorage.getItem('rbaclogin1')
  useEffect(() => {
    const routeTree = buildRouteTree(JSON.parse(rbaclogin));
    setRoutes(routeTree);
    console.log(routeTree, '修改后的路由树')
  }, []);
  
  const menuItems = generateMenuItems(routes);
  const toMenuList = ({ key }: { key: string }) => {
    navigate(key);
  };

  // 获取用户名
  const superusername = localStorage.getItem('superusername')
  // 退出登录  
  const edmit = () => {
    localStorage.clear()
    navigate('/login')
  }
  const location = useLocation(); // 获取当前路由位置
  // 根据当前路由路径生成面包屑项
  const generateBreadcrumbItems = (routes: RouteItem[], currentPath: string): React.ReactNode[] => {
    const breadcrumbItems: React.ReactNode[] = [];
    for (const route of routes) {
      if (currentPath.startsWith(route.path)) {
        breadcrumbItems.push(<Breadcrumb.Item key={route.path}>{route.title}</Breadcrumb.Item>);
        if (route.children) {
          const childrenBreadcrumbItems = generateBreadcrumbItems(route.children, currentPath);
          breadcrumbItems.push(...childrenBreadcrumbItems);
        }
      }
    }
    return breadcrumbItems;
  }

  const [isDarkTheme, setIsDarkTheme] = useState(false);

  // localStorage.setItem('flag', 'light'); // 切换主题
  useEffect(() => {
    const storedTheme = localStorage.getItem('theme');
    if (storedTheme === 'dark') {
      setIsDarkTheme(true);
    } else {
      setIsDarkTheme(false);
    }
  }, []);
  localStorage.setItem('flag', isDarkTheme ? 'true' : 'false');
  const toggleTheme = () => {
    if (!isDarkTheme) {
      document.documentElement.classList.remove('dark');
      document.documentElement.classList.add('light');
    } else {
      document.documentElement.classList.remove('light');
      document.documentElement.classList.add('dark');
    }
    setIsDarkTheme(!isDarkTheme);
  };

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider theme={isDarkTheme ? 'dark' : 'light'} collapsible collapsed={collapsed} onCollapse={setCollapsed}>
        <div className="demo-logo-vertical" />
        <Menu
          theme={isDarkTheme ? 'dark' : 'light'}
          defaultSelectedKeys={["1"]}
          mode="inline"
          items={menuItems}
          onClick={toMenuList}
        />
      </Sider>
      <Layout>
        <Header style={{
          backgroundColor: isDarkTheme ? '#001529' : '#fff',
          color: isDarkTheme ? '#fff' : '#001529',
          padding: 0,
        }} >
          <div style={{
            display: "flex",
            justifyContent: "flex-end",
            alignItems: 'center',
          }}>
            <div>
              <span onClick={edmit}>
                <svg style={{
                  width: '3rem',
                  height: '2rem',
                  marginTop: '1.5rem',
                  display:'inline-block',
                }}t="1733206920301" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2997" width="200" height="200"><path d="M515.7 919.3c-55.9 0-110-10.9-161.1-32.5-49.3-20.8-93.5-50.7-131.5-88.7s-67.8-82.2-88.7-131.5c-21.6-51-32.5-105.2-32.5-161.1 0-86.6 26.5-169.5 76.5-239.8 24.1-33.8 53.1-63.8 86.1-89 33.4-25.5 70.2-45.7 109.5-60 13-4.7 27.3 2 32 14.9s-2 27.3-14.9 32C248 215.7 151.8 353.1 151.8 505.5c0 200.6 163.2 363.8 363.8 363.8 200.6 0 363.8-163.2 363.8-363.8 0-156.7-99.8-295.4-248.2-345.1-13.1-4.4-20.2-18.6-15.8-31.6 4.4-13.1 18.5-20.2 31.6-15.8 40.6 13.6 78.7 33.4 113.4 58.8 34.2 25.1 64.3 55.3 89.3 89.5 52.1 71.2 79.7 155.6 79.7 244.1 0 55.9-10.9 110-32.5 161.1-20.8 49.3-50.7 93.5-88.7 131.5s-82.2 67.8-131.5 88.7c-51 21.6-105.2 32.6-161 32.6z" fill="#0CC6BF" p-id="2998"></path><path d="M510.9 530.5c-16.6 0-30-13.4-30-30V116.7c0-16.6 13.4-30 30-30s30 13.4 30 30v383.8c0 16.5-13.5 30-30 30z" fill="#0CC6BF" p-id="2999"></path></svg>
              </span>
              
            </div>
            <div style={{ marginRight: '1rem' }}>
              <Button onClick={toggleTheme}>
                {isDarkTheme ? '切换到浅色主题' : '切换到深色主题'}
              </Button>
            </div>
            <div>
              <span style={{ fontSize: 20, fontWeight: 'bold' }}>欢迎您，{superusername}！</span>

            </div>

            <div style={{
              width: '70px',
              height: '70px',
              // display: 'flex',
            }}>

              <img style={{
                width: '50px',
                height: '50px',
                marginTop: '2px',
                borderRadius: '50%',
              }} src="https://tse1-mm.cn.bing.net/th/id/OIP-C.rx9ecay-IlKbXyEtssGcRAHaHF?w=212&h=203&c=7&r=0&o=5&dpr=1.1&pid=1.7" alt="" />
            </div>
          </div>
        </Header>
        <Content style={{
          backgroundColor: isDarkTheme ? '#001529' : '#fff',
          // color: isDarkTheme ? '#fff' : '#000',
          padding: "0 16px"
        }}>
          <Breadcrumb style={{
            margin: "16px 0", backgroundColor: isDarkTheme ? '#001529' : '#fff',
            color: isDarkTheme ? '#fff' : '#001529',
          }}>
            {generateBreadcrumbItems(routerList, location.pathname)}
          </Breadcrumb>
          <div
            style={{
              padding: 24,
              minHeight: 360,
              backgroundColor: isDarkTheme ? '#001529' : '#fff',
              color: isDarkTheme ? '#fff' : '#001529',
            }}
          >
            <Outlet />
          </div>
        </Content>
        <Footer style={{
          textAlign: "center",
          backgroundColor: isDarkTheme ? '#001529' : '#fff',
          color: isDarkTheme ? '#fff' : '#001529',
        }}>
          Ant Design ©{new Date().getFullYear()} Created by Ant UED
        </Footer>
      </Layout>
    </Layout >
  );

};

export default Home;
